<template>
	<base-page class="base-form online-work-order-form" :title="form.formName" @back="goBack">
		<u-row class="filter-box" type="flex" align="center">
			<view class="search">
				<view class="dropdown">
					<u-dropdown ref="dropdown" menu-icon="arrow-down-fill"
						menu-icon-size="20" inactive-color="#323233" title-size="30" :close-on-click-mask="false">
						<u-dropdown-item :title="getFilterStatusName" v-model="formFilter.flowStatus" :options="flowStatusDropdownList"
							@change="deopdownChange">
						</u-dropdown-item>
					</u-dropdown>
				</view>
				<!-- <p class="line"></p> -->
				<u-search style="padding: 0px; flex-grow: 1;"
					shape="square" bg-color="#F7F8FA" placeholder-color="#c8c9cc"
					:show-action="false" v-model="formFilter.workOrderCode"
					placeholder="请输入工单编码"
					@search="onRefresh"
				/>
			</view>
		</u-row>
		<view class="main-box">
			<view class="list" style="height: 500px;">
				<custom-list
					ref="cardList"
					height="100%"
					:isLoading="tableWidget.loading"
          :finished="tableWidget.finished"
          :dataList="tableWidget.dataList"
          @load="tableWidget.loadDataList"
				>
					<view class="list-item" v-for="(data, index) in tableWidget.dataList" :key="index">
						<TaskCard class="card-item" :cardData="getCardData(data)"
							:flowStatus="data.flowStatus">
							<view slot="menu" class="task-menu-box">
								<u-button class="menu-btn"
									:hair-line="false"
									:custom-style="BtnCustomStyle1"
									@click.stop="onCancelWorkOrder(data)"
								>
									撤销
								</u-button>
								<u-button class="menu-btn" color="#07C160" plain
									:hair-line="false"
									:custom-style="BtnCustomStyle2"
									@click.stop="onHandlerRemindClick(data)"
								>
									催办
								</u-button>

								<u-button class="menu-btn" type="default"
									:custom-style="BtnCustomStyle"
									v-if="getPrintOperation"
									:class="getPrintOperation.btnClass"
									@click.stop="onPrint(getPrintOperation, data)"
								>
									{{getPrintOperation.name || '打印'}}
								</u-button>
								<!-- v-if="(data.initTaskInfo || {}).taskKey !== (data.runtimeTaskInfo || {}).taskKey" -->
								<u-button class="menu-btn"
									:custom-style="BtnCustomStyle"
									v-if="(data.initTaskInfo.taskKey ||'') != (data.runtimeTaskInfo.taskKey || '')"
									type="primary"
									@click.stop="onViewWorkOrder(data)"
								>
									详情
								</u-button>
								<!-- v-if="(data.initTaskInfo || {}).taskKey === (data.runtimeTaskInfo || {}).taskKey" -->
								<u-button class="menu-btn" type="primary"
									:custom-style="BtnCustomStyle"
									v-if="(data.initTaskInfo.taskKey || '') === (data.runtimeTaskInfo.taskKey || '')"
									@click.stop="onHandlerWorkOrder(data)"
								>
									办理
								</u-button>
							</view>
						</TaskCard>
					</view>
				</custom-list>
			</view>
		</view>
		<view class="addBtn" @click="onStartFlow()">
			<image class="addImg" src="../../static/icon/addIcon.png" mode=""></image>
		</view>
	</base-page>
</template>

<script>
	import {
		findItemFromList
	} from '@/utils';
	import { FlowOperationController, FlowEntryController } from '@/api/flowController.js';
	import TaskCard from '@/views/components/taskCard.vue';
	import {
		OnlineFormMixins
	} from './onlineFormMixins.js';
	import { DropdownWidget, TableWidget } from '@/utils/widget.js';

	export default {
		name: 'OnlineWorkOrderForm',
		props: {
			entryId: {
				type: String
			},
			formConfig: {
				type: Object,
				required: true
			}
		},
		options: { styleIsolation: 'shared' },
		mixins: [OnlineFormMixins],
		components: {
			TaskCard
		},
		provide() {
			return {
				form: () => {
					return {
						...this.form,
						getWidgetValue: this.getWidgetValue
					}
				}
			}
		},
		data() {
			return {
				isReady: false,
				isUpdateFrom:0,
				showStatusFilter: false,
				processDefinitionKey: undefined,
				processDefinitionName: undefined,
				formFilter: {
					workOrderCode: undefined,
					flowStatus: undefined
				},
				tableWidget: new TableWidget(this.loadTableData, this.loadTableDataVerify, true),
				dropdownName:'全部',
				pageNum: 1,
				BtnCustomStyle:{
					'width': '128rpx',
					'height': '64rpx',
					'borderRadius': '8rpx',
					'fontSize':'24rpx'
				},
				BtnCustomStyle1:{
					'width': '128rpx',
					'height': '64rpx',
					'borderRadius': '8rpx',
					'background':'#ffffff',
					'border':'1px solid #EE0A24',
					'color':'#EE0A24',
					'fontSize':'24rpx'
				},
				BtnCustomStyle2:{
					'width': '128rpx',
					'height': '64rpx',
					'borderRadius': '8rpx',
					'background':'#ffffff',
					'border':'1px solid #07C160',
					'color':'#07C160',
					'fontSize':'24rpx'
				}
			}
		},
		methods: {
			goBack(){
				uni.navigateBack();
			},
			onBack() {
				this.$router.replace({
					name: 'home'
				});
			},
			onRefresh() {
				this.pageNum = 1;
				if (this.$refs.cardList) this.$refs.cardList.reset();
			},
			deopdownChange(e) {
				if (e === undefined) {
					this.dropdownName = '全部'
				} else{
					this.flowStatusDropdownList.forEach(v=>{
						if (v.id === e) {
							this.dropdownName = v.name
						}
					})
				}
				this.onRefresh();
			},
			getCardData(cardData) {
				// console.log(cardData)
				return {
					title: cardData.processDefinitionName,
					subTitle: [
						'工单编号：' + (cardData.workOrderCode || '无'),
						'发起人：' + (cardData.userShowName || '无'),
						'当前任务：' + ((cardData.runtimeTaskInfo || {}).taskName || '无'),
						'创建日期：' + (cardData.createTime || '无')
					]
				}
			},
			loadTableDataVerify() {
				return true;
			},
			async loadTableData(params) {
				try {
					if (params == null) params = {};
					params = {
						...params,
						flowWorkOrderDtoFilter: {
							flowStatus: this.formFilter.flowStatus,
							workOrderCode: this.formFilter.workOrderCode
						}
					}
					// 脱敏设置
					params.ignoreMaskFields = this.getIgnoreMaskFields();
					if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] === 'function') {
						params = await this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](params);
					}
					if (params == null) {
						throw new Error('取消加载数据');
					}
					let res = await FlowOperationController.listWorkOrder(this, params, {
						processDefinitionKey: this.processDefinitionKey
					});
					res.dataList = res.dataList.map(item => {
						let initTaskInfo = item.initTaskInfo == null ? {} : JSON.parse(item.initTaskInfo);
						let runtimeTaskInfo = (Array.isArray(item.runtimeTaskInfoList) && item.runtimeTaskInfoList.length > 0) ? item.runtimeTaskInfoList[0] : {};
						return {
							...item,
							flowStatusShowName: this.SysFlowWorkOrderStatus.getValue(item
								.flowStatus),
							initTaskInfo,
							runtimeTaskInfo
						}
					});
					if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function') {
						res.dataList = await this.queryTable.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA](res.dataList);
					}
					return {
						dataList: res.dataList,
						totalCount: res.totalCount
					};
				} catch (e) {
					console.error(e);
					throw e;
				}
			},
			getListParent(sender) {
				return sender.$parent.$parent;
			},
			onStartFlow() {
				if (this.processDefinitionKey == null) return;
				let params = {
					processDefinitionKey: this.processDefinitionKey
				}
				FlowOperationController.viewInitialTaskInfo(this, params).then(res => {
					if (res && res.taskType === this.SysFlowTaskType.USER_TASK && res.assignedMe) {
						const data = {
							processDefinitionKey: this.processDefinitionKey,
							formId: res.formId,
							routerName: res.mobileRouterName || res.routerName,
							readOnly: res.readOnly,
							taskName: '启动流程',
							isDraft: true,
							flowEntryName: this.processDefinitionName,
							operationList: (res.operationList || []).filter(item => {
								return item.type !== this.SysFlowTaskOperationType.CO_SIGN &&
									item.type !== this.SysFlowTaskOperationType.REVOKE && item
									.type !== this.SysFlowTaskOperationType.SIGN_REDUCTION;
							}),
							variableList: res.variableList
						}
						uni.navigateTo({
							url: '/views/workflow/handleFlowTask/index?passData=' + encodeURIComponent(JSON.stringify(
								data))
						})
					} else {
						FlowOperationController.startOnly(this, {
							processDefinitionKey: this.processDefinitionKey
						}).then(res => {
							uni.showToast({
								icon: 'success',
								title: '启动成功！'
							})
						}).catch(e => {});
					}
				}).catch(e => {});
			},
			onHandlerWorkOrder(row) {
				if (this.processDefinitionKey == null) return;
				let taskId = (Array.isArray(row.runtimeTaskInfoList) && row.runtimeTaskInfoList.length > 0) ? row
					.runtimeTaskInfoList[0].taskId : undefined;
				let params = {
					processInstanceId: row.processInstanceId,
					processDefinitionId: row.processDefinitionId,
					taskId: taskId
				}
				FlowOperationController.viewRuntimeTaskInfo(this, params).then(res => {
					const data = {
						isRuntime: true,
						isDraft: row.flowStatus === this.SysFlowWorkOrderStatus.DRAFT,
						flowStatus: row.flowStatus,
						taskId: taskId,
						processDefinitionKey: row.processDefinitionKey,
						processInstanceId: row.processInstanceId,
						processDefinitionId: row.processDefinitionId,
						formId: res.formId,
						routerName: res.mobileRouterName || res.routerName,
						readOnly: res.readOnly,
						taskName: (row.runtimeInitialTask || {}).taskName,
						flowEntryName: row.processDefinitionName,
						processInstanceInitiator: row.processInstanceInitiator,
						operationList: (res.operationList || []).filter(item => item.type !==
							this.SysFlowTaskOperationType.CO_SIGN),
						variableList: res.variableList
					}
					uni.navigateTo({
						url: '/views/workflow/handleFlowTask/index?passData=' + encodeURIComponent(JSON.stringify(
							data))
					})
				}).catch(e => {});
			},
			onViewWorkOrder(row) {
				if (this.processDefinitionKey == null) return;
				FlowOperationController.viewInitialHistoricTaskInfo(this, {
					processInstanceId: row.processInstanceId
				}).then(res => {
						const data = {
							isRuntime: false,
							flowStatus: row.flowStatus,
							processDefinitionKey: row.processDefinitionKey,
							processInstanceId: row.processInstanceId,
							processDefinitionId: row.processDefinitionId,
							formId: res.formId,
							routerName: res.mobileRouterName || res.routerName,
							readOnly: true,
							taskId: row.runtimeTaskInfo.taskId,
							taskName: row.runtimeTaskInfo.taskName,
							flowEntryName: row.processDefinitionName,
							processInstanceInitiator: row.userShowName,
							headImageUrl: row.headImageUrl
						}

						uni.navigateTo({
							url: '/views/workflow/handleFlowTask/index?passData=' + encodeURIComponent(JSON
								.stringify(
									data))
						})
					}).catch((e)=>{
						console.log(e)
					})
			},
			onHandlerRemindClick(row) {
				console.log(row.workOrderId)
				FlowOperationController.remindRuntimeTask(this, {
					workOrderId: row.workOrderId
				}).then(res => {
					// this.$refs.uToast.show({
					// 	title: '催办成功！',
					// 	type: 'success',
					// })
					uni.showToast({
						title: '催办成功！',
						duration: 1500
					})
				}).catch(e => {});
			},
			onCancelWorkOrder(row) {
				uni.showModal({
					title: '消息',
					content: '是否撤销此工单？',
					success: (res) => {
						if(res.confirm) {
							//点击确定之后执行的代码
							let params = {
								workOrderId: row.workOrderId,
								cancelReason: '主动撤销'
							}
							FlowOperationController.cancelWorkOrder(this, params).then(res => {
								this.$refs.uToast.show({
									title: '撤销成功！',
									type: 'success'
								})
								this.onSearch();
							}).catch(e => {});
						} else {
							console.log('cancel') //点击取消之后执行的代码
						}
					}
				})
			}
		},
		computed: {
			form() {
				this.isUpdateFrom++
				let temp = this.buildFormConfig(this.formConfig);
				return temp;
			},
			queryTable() {
				return this.form.tableWidget;
			},
			getPrintOperation() {
				let operation = findItemFromList(this.form.operationList, this.SysCustomWidgetOperationType.PRINT, 'type');
				return (operation && operation.enabled) ? operation : null;
			},
			getFilterStatusName() {
				return this.SysFlowWorkOrderStatus.getValue(this.formFilter.flowStatus) || '全部';
			},
			flowStatusDropdownList() {
				let tempList = this.SysFlowWorkOrderStatus.getList().map(item => {
					return {
						...item,
						label: item.name,
						value: item.id
					}
				});
				tempList.unshift({
					id: undefined,
					label: '全部',
					value: undefined
				});
				return tempList;
			}
		},
		watch: {
			isUpdateFrom: {
				handler() {
					this.isReady = false;
					this.initPage();
					this.initFormWidgetList();
					if (this.entryId) {
						FlowEntryController.viewDict(this, {
							entryId: this.entryId
						}).then(res => {
							this.processDefinitionKey = res.processDefinitionKey;
							this.processDefinitionName = res.processDefinitionName;
							this.isReady = true;
							this.$refs.cardList.reset();
						}).catch(e => {
						});
					} else {
						this.isReady = true;
					}
				},
				immediate: true
			}
		},
	}
</script>
<style scoped lang="scss">
	.addBtn{
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: $u-type-primary;
		position: fixed;
		left: 16px;
		bottom: 100px;
		z-index: 999;
		.addImg{
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>
<style scoped>
	.search{
		display: flex;
		width: 100%;
		flex-direction: row;
		align-items: center;
	}
	.search .dropdown{
		width: 20%;
	}
	::v-deep .u-dropdown__content{
		width: 200rpx !important;
		left: -31rpx !important;
	}
	::v-deep .u-dropdown__content__mask{
		display: none;
	}
	.search-label {
		height: 68rpx;
		width: 170rpx;
		background: #F7F8FA;
		/* border-right: 2px solid #ff7700; */
		display: flex;
		flex-direction: row;
		/* position: relative; */
	}

	.search-label .line {
		height: 40rpx;
		width: 0;
		margin: auto 0px auto 0;
		border-right: 1px solid #d9dbde;
		z-index: 999;
	}

	.card-item+.card-item {
		margin-top: 32rpx;
	}

	.online-work-order-form {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #F6F7F9;
	}

	.task-menu-box {
		border-top: 1px solid #E8E8E8;
		padding-top: 16rpx;
		margin-top: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
	}

	.menu-btn {
		width: 128rpx;
		border-radius: 8rpx;
	}

	.menu-btn+.menu-btn {
		margin-left: 16rpx;
	}
	.main-box {
		display: flex;
		flex-direction: column;
		height: 100%;
	}
	.filter-box {
		background: white;
		padding: 0px 36rpx;
		flex-grow: 0;
		flex-shrink: 0;
	}
	.list {
		flex-grow: 1;
		flex-shrink: 1;
		padding: 4rpx 32rpx 32rpx 32rpx;
		position: relative;
	}
	.list-item {
		margin: 32rpx 0;
	}
</style>
<style>
	.uicon-arrow-down-fill{
		color: #323233 !important;
		top:4rpx !important;
	}
</style>
